import { Model, DataTypes } from 'sequelize';
import sequelize from '@/config/database';
import Role from './role.model';
import Menu from './menu.model';

// 定义角色菜单关联属性接口
interface RoleMenuAttributes {
  roleId: number;
  menuId: number;
}

// 角色菜单关联模型类
class RoleMenu extends Model<RoleMenuAttributes> implements RoleMenuAttributes {
  public roleId!: number;
  public menuId!: number;

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

RoleMenu.init(
  {
    roleId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'role_id',
      references: {
        model: Role,
        key: 'role_id'
      }
    },
    menuId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      field: 'menu_id',
      references: {
        model: Menu,
        key: 'menu_id'
      }
    }
  },
  {
    sequelize,
    tableName: 'sys_role_menu',
    timestamps: false
  }
);

// 建立关联关系
Role.belongsToMany(Menu, {
  through: RoleMenu,
  foreignKey: 'roleId',
  otherKey: 'menuId'
});

Menu.belongsToMany(Role, {
  through: RoleMenu,
  foreignKey: 'menuId',
  otherKey: 'roleId'
});

// 为RoleMenu添加Menu关联以便在查询时使用
RoleMenu.belongsTo(Menu, {
  foreignKey: 'menuId',
  as: 'Menu'
});

// 为RoleMenu添加Role关联
RoleMenu.belongsTo(Role, {
  foreignKey: 'roleId',
  as: 'Role'
});

export default RoleMenu;